package com.dau.api;

import com.dau.common.result.R;
import com.dau.common.util.GlobalConstants;
import com.dau.entity.customer.LuckyDraw;
import com.dau.entity.system.prize.SysPrize;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 测试
 *
 * @author tzj
 * @date 2024/12/18
 */
@SpringBootTest
public class SpringBootTestDemo {
    @Test
    public void testDemo() {
        List<SysPrize> list = new ArrayList<>();
        //获取指定元素（属性=0）直到不是0
        list.stream().takeWhile(prize -> GlobalConstants.ZERO_STR.equals(prize.getGuaranteedReward())).collect(Collectors.toList());
        list.stream().dropWhile(prize -> GlobalConstants.ZERO_STR.equals(prize.getGuaranteedReward())).collect(Collectors.toList());
        System.out.println();
    }

    @Test
    public void draw() throws Exception {
///设置线程池最大执行20个线程并发执行任务
        int threadSize = 200;
        //AtomicInteger通过CAS操作能保证统计数量的原子性
        AtomicInteger successCount = new AtomicInteger(0);
        CountDownLatch downLatch = new CountDownLatch(200);
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(threadSize);
        for (int i = 0; i < threadSize; i++) {
            fixedThreadPool.submit(() -> {
                RestTemplate restTemplate = new RestTemplate();
                R str = restTemplate.getForObject("http://localhost:8080/api/luckyDraw/go?activityId=1", R.class);
                if (200 == (str.getCode())) {
                    successCount.incrementAndGet();
                }
                ObjectMapper objectMapper = new ObjectMapper();
                try {
                    String s = formatJsonString(str.getData().toString());
                    LuckyDraw luckyDraw = objectMapper.readValue(s, LuckyDraw.class);
                    System.out.println(luckyDraw.getPrizeName());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                downLatch.countDown();
            });
            //模拟网络传输时间
            Thread.sleep(100);
        }
        //等待所有线程都执行完任务
        downLatch.await();
        fixedThreadPool.shutdown();
        System.out.println("总共有" + successCount.get() + "个线程请求成功!");
    }

    private static String formatJsonString(String jsonString) {
        // 将 = 替换为 :
        jsonString = jsonString.replace("=", ":");

        // 将键和字符串值用双引号括起来
        jsonString = jsonString.replaceAll("(\\w+):", "\"$1\":");
        jsonString = jsonString.replaceAll(":([^,}]+)(?=,|})", ":\"$1\"");

        return jsonString;
    }

    //重复提交
    @Test
    public void hell1() throws Exception {
///设置线程池最大执行20个线程并发执行任务
        int threadSize = 20;
        //AtomicInteger通过CAS操作能保证统计数量的原子性
        AtomicInteger successCount = new AtomicInteger(0);
        CountDownLatch downLatch = new CountDownLatch(20);
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(threadSize);
        for (int i = 0; i < threadSize; i++) {
            fixedThreadPool.submit(() -> {
                RestTemplate restTemplate = new RestTemplate();
                String str = restTemplate.getForObject("http://localhost:8080/api/test", String.class);
                if ("success".equals(str)) {
                    successCount.incrementAndGet();
                }
                System.out.println(str);
                downLatch.countDown();
            });
            //模拟网络传输时间
            Thread.sleep(100);
        }
        //等待所有线程都执行完任务
        downLatch.await();
        fixedThreadPool.shutdown();
        System.out.println("总共有" + successCount.get() + "个线程请求成功!");
    }

    //限流
    @Test
    public void hell0() throws Exception {
        ///设置线程池最大执行20个线程并发执行任务
        int threadSize = 20;
        //AtomicInteger通过CAS操作能保证统计数量的原子性
        AtomicInteger successCount = new AtomicInteger(0);
        CountDownLatch downLatch = new CountDownLatch(20);
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(threadSize);
        for (int i = 0; i < threadSize; i++) {
            fixedThreadPool.submit(() -> {
                RestTemplate restTemplate = new RestTemplate();
                String str = restTemplate.getForObject("http://localhost:8080/api/test", String.class);
                if ("success".equals(str)) {
                    successCount.incrementAndGet();
                }
                System.out.println(str);
                downLatch.countDown();
            });
        }
        //等待所有线程都执行完任务
        downLatch.await();
        fixedThreadPool.shutdown();
        System.out.println("总共有" + successCount.get() + "个线程获得到了令牌!");
    }
}
